<?php

namespace App\Console\Commands\Shop;

use App\Kuafu\Guanyuan\Service\GuanyuanService;
use App\Kuafu\Shop\Model\Shop;
use App\Kuafu\Shop\Model\ShopBusinessModel;
use App\Library\KfHttp\TigerCurl;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class ShopBusiness extends Command
{
    /**
     *The nameand signature of the console command.
     *
     * @var string
     */
    protected $signature = 'shop:shop_business_update';

    /**
     *The console command description.
     *
     * @var string
     */
    protected $description = '更新门店昨日营业数据';

    /**
     *Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     *Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $data = GuanyuanService::getShopBusinessData(Carbon::now()->subDay()->format('Y-m-d'));

        $insertData = [];

        foreach ($data as $datum) {
            $shopBusinessModel['deliveryType']                = (string)$datum['投放类型'];
            $shopBusinessModel['deliveryTime']                = (string)$datum['投放开始时间'];
            $shopBusinessModel['shopType']                    = (string)$datum['门店类型'];
            $shopBusinessModel['shopName']                    = (string)$datum['门店名称'];
            $shopBusinessModel['shopCode']                    = (int)$datum['门店编码'];
            $shopBusinessModel['region']                      = (string)$datum['区域'];
            $shopBusinessModel['date']                        = (string)$datum['日期'];
            $shopBusinessModel['orderNum']                    = (int)$datum['订单量'];
            $shopBusinessModel['newOpen']                     = (string)$datum['是否本月新开'];
            $shopBusinessModel['dailyManpower']               = (float)$datum['日人工'];
            $shopBusinessModel['dailyEnergy']                 = (float)$datum['日能源'];
            $shopBusinessModel['roi']                         = (float)$datum['roi'];
            $shopBusinessModel['estimatedProfit']             = (float)$datum['预估利润'];
            $shopBusinessModel['openMonthLong']               = (float)$datum['开业时长（月）'];
            $shopBusinessModel['openDaysLong']                = (int)$datum['开业时长（天）'];
            $shopBusinessModel['shopArea']                    = (float)$datum['门店面积'];
            $shopBusinessModel['orderTurnover']               = (float)$datum['订单营业额'];
            $shopBusinessModel['orderOfferAmount']            = (float)$datum['订单优惠金额'];
            $shopBusinessModel['orderReceivedAmount']         = (float)$datum['订单实收金额'];
            $shopBusinessModel['staffNum']                    = (int)$datum['员工人数'];
            $shopBusinessModel['province']                    = (string)$datum['省份'];
            $shopBusinessModel['city']                        = (string)$datum['城市'];
            $shopBusinessModel['takeawayOrderTurnover']       = (float)$datum['外卖订单营业额'];
            $shopBusinessModel['takeawayOrderOfferAmount']    = (float)$datum['外卖订单优惠金额'];
            $shopBusinessModel['takeawayOrderReceivedAmount'] = (float)$datum['外卖订单实收金额'];
            $shopBusinessModel['canteenOrderTurnover']        = (float)$datum['堂食订单营业额'];
            $shopBusinessModel['canteenOrderOfferAmount']     = (float)$datum['堂食订单优惠金额'];
            $shopBusinessModel['canteenOrderReceivedAmount']  = (float)$datum['堂食订单实收金额'];
            $shopBusinessModel['canteenEstimatedProfit']      = (float)$datum['堂食预估利润'];
            $shopBusinessModel['takeawayEstimatedProfit']     = (float)$datum['外卖预估利润'];
            $shopBusinessModel['canteenOrderNum']             = (int)$datum['堂食订单量'];
            $shopBusinessModel['takeawayOrderNum']            = (int)$datum['外卖订单量'];
            $shopBusinessModel['openBusinessDate']            = (string)$datum['开业日期'];
            $shopBusinessModel['closureTime']                 = (string)$datum['闭店时间'];
            $shopBusinessModel['franchiseeName']              = (string)$datum['加盟商'];
            $shopBusinessModel['dailyRent']                   = (float)$datum['日房租'];
            $shopBusinessModel['rent']                        = (float)$datum['房租'];
            $shopBusinessModel['district']                    = (string)$datum['区县'];
            $shopBusinessModel['shopActiveStatus']            = (string)$datum['门店活跃状态'];
            $shopBusinessModel['status']                      = (string)$datum['状态'];
            $shopBusinessModel['manpower']                    = (int)$datum['人工'];
            $shopBusinessModel['preservationPoint']           = (float)$datum['保本点'];
            $shopBusinessModel['monthBusinessDays']           = (int)$datum['月营业天数'];
            $shopBusinessModel['dailyIncome']                 = (float)$datum['日均实收'];
            $shopBusinessModel['monthDays']                   = (int)$datum['实际月天数'];
            $shopBusinessModel['thisYearClose']               = (string)$datum['是否本年闭店'];
            $shopBusinessModel['shopAddress']                 = (string)$datum['店铺地址'];
            $shopBusinessModel['cityGrade']                   = (string)$datum['城市等级'];
            $shopBusinessModel['roiGrade']                    = (string)$datum['ROI分类'];
            $shopBusinessModel['franchiseeRealName']          = (string)$datum['加盟商真名'];
            $shopBusinessModel['dailyRentCost']               = (float)$datum['日房租成本'];
            $shopBusinessModel['headOperations']              = (string)$datum['运营负责人'];
            $shopBusinessModel['privateDomain']               = (string)$datum['私域'];
            $shopBusinessModel['mtOrderNum']                  = (int)$datum['美团订单量'];
            $shopBusinessModel['elmOrderNum']                 = (int)$datum['饿了么订单量'];
            $shopBusinessModel['agencyOperationStatus']       = (string)$datum['代运营状态'];
            $shopBusinessModel['averageDailyProfit']          = (float)$datum['日均利润'];
            $shopBusinessModel['receivedGrade']               = (int)$datum['实收分级'];
            $shopBusinessModel['profitGrade']                 = (int)$datum['利润分级'];
            $shopBusinessModel['weightRoi']                   = (float)$datum['加权ROI'];
            $shopBusinessModel['loss']                        = (string)$datum['是否亏损'];
            $shopBusinessModel['shopGrade']                   = (string)$datum['门店分级'];
            $shopBusinessModel['siteLocationType']            = (string)$datum['选址分类'];
            $shopBusinessModel['elmRating']                   = (float)$datum['饿了么评分'];
            $shopBusinessModel['mtRating']                    = (float)$datum['美团评分'];
            $shopBusinessModel['cashierSystem']               = (string)$datum['收银系统'];
            $shopBusinessModel['elmShopId']                   = (int)$datum['waimaiShopId-饿'];
            $shopBusinessModel['elmShopName']                 = (string)$datum['waimaiShopName-饿'];
            $shopBusinessModel['mtShopId']                    = (int)$datum['waimaiShopId-美'];
            $shopBusinessModel['mtShopName']                  = (string)$datum['waimaiShopName-美'];
            $shopBusinessModel['takeawayOpenTime']            = (string)$datum['外卖介入时间'];
            $shopBusinessModel['takeawayShopStatus']          = (string)$datum['外卖新店判断'];
            $shopBusinessModel['performanceRange']            = (string)$datum['业绩区间'];
            $shopBusinessModel['activityType']                = (string)$datum['活动类型'];
            $shopBusinessModel['shopAreaType']                = (string)$datum['铺位类型'];
            $shopBusinessModel['takeawayBusinessDays']        = (int)$datum['外卖营业天数'];
            $shopBusinessModel['createdAt']                   = time();

            $insertData[] = $shopBusinessModel;

            $this->info(time() . (string)$datum['门店名称']);
        }

        // 门店code->门店id
        $shopCodes = Shop::query()->pluck('id', 'shopCode')->toArray();

        // 订货比
        $orderRatioList = [];
        $i              = 1;
        do {
            $tigerData = TigerCurl::getIns()
                                  ->do('internal/shop/orderRatio', ['pageSize' => 1000, 'pageNum' => $i],
                                      'GET')['data'] ?? [];

            $orderRatioList = array_merge($orderRatioList, $tigerData);
            $i++;

        } while ($tigerData);
        $orderRatioList = collect($orderRatioList)->keyBy('shopId');

        // 最后巡店时间
        $i              = 1;
        $lastCruiseList = [];
        do {
            $tigerData      = TigerCurl::getIns()
                                       ->do('internal/shop/lastCruiseTime', ['pageSize' => 1000, 'pageNum' => $i],
                                           'GET')['data'] ?? [];
            $lastCruiseList = array_merge($lastCruiseList, $tigerData);
            $i++;

        } while ($tigerData);
        $lastCruiseList = collect($lastCruiseList)->keyBy('shopId');

        // 装备数据
        foreach ($insertData as &$v) {
            $v['turnoverAmount'] = $v['orderAmount'] = $v['orderRatio'] = $v['lastCruiseTime'] = 0;

            $v['shopId'] = $shopCodes[$v['shopCode']] ?? 0;
            if (!$v['shopId']) {
                continue;
            }

            $shop = $orderRatioList[$v['shopId']] ?? [];
            if ($shop) {
                $v['turnoverAmount'] = round($shop['turnover'] / 100);
                $v['orderAmount']    = round($shop['orderAmount'] / 100);
                $v['orderRatio']     = $shop['orderRatio'];
            }

            $v['lastCruiseTime'] = $lastCruiseList[$v['shopId']]['submitTime'] ?? 0;
        }

        // update
        DB::beginTransaction();

        collect($insertData)->each(function ($item) {
            ShopBusinessModel::query()->where('shopCode', $item['shopCode'])->update([
                'isNew' => ShopBusinessModel::IS_NEW_OFF
            ]);
            ShopBusinessModel::query()->updateOrCreate(['shopCode' => $item['shopCode'], 'date' => $item['date']],
                array_merge($item, ['isNew' => ShopBusinessModel::IS_NEW_ON]));
        });

        //删除已更新的60天外的数据
        $day = Carbon::now()->subDays(60)->toDateString();
        ShopBusinessModel::query()->where('date', '<', $day)->where('isNew', 0)->delete();

        DB::commit();

        $this->info('完成');
    }
}
